package channel;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import datasource.ConnectionSSH2;
/**
 * 文件上传管道
 *
 * @version 1.0
 * @since JDK1.7
 * @author yutao
 * @company 上海朝阳永续信息技术有限公司
 * @copyright (c) 2016 SunTime Co'Ltd Inc.All rights reserved.
 * @date 2017年5月3日下午5:54:59
 */
public class SFTPChannel {

	private Session session = null;
	private Channel channel = null;
	private Logger logger = LogManager.getLogger(SFTPChannel.class);
	private String host;
	private int port;
	private String username;
	
	
	public SFTPChannel() {
		this.session = ConnectionSSH2.dataSource.getSession();
	}
	
	public SFTPChannel(String serverip, int port, String username) {
		this.host = serverip;
		this.port = port;
		this.username = username;
		this.session = ConnectionSSH2.dataSource.getSession(serverip, port, username);
	}

	/**
	 * 打开sftp管道,用于文件上传
	 * @return
	 * @throws JSchException
	 * @author yutao
	 * @date 2017年4月18日下午4:58:47
	 */
	public ChannelSftp getChannelSftp() {
		try {
			if(!session.isConnected()){
				this.session = ConnectionSSH2.dataSource.getSession(this.host, this.port, this.username);
			}
			channel = session.openChannel("sftp");
			channel.connect();
		} catch (JSchException e) {
			logger.error("------SFTPChannel----connect----sftp----" + e.getStackTrace() + "----message----" + e.getMessage());
			e.printStackTrace();
		}
		return (ChannelSftp) channel;
	}
	
	/**
	 * 获得session
	 * @param path
	 * @param host
	 * @param port
	 * @return
	 * @author yutao
	 * @date 2017年4月26日下午1:26:40
	 */
	public Session getSession(){
//		this.session = ConnectionSSH2.dataSource.getSession();
		return session;
	}
	
	
	/**
	 * 关闭管道
	 * 
	 * @author yutao
	 * @date 2017年4月26日下午1:26:51
	 */
	public void closeChannel(){
		if(channel != null){
			channel.disconnect();
		}
	}
	
}
